<?php


namespace app\admin\logic\system;



use app\common\enum\SysEnum;
use app\common\model\system\SysRole;
use app\common\model\system\SysUser;
use app\common\model\system\SysUserGroup;
use app\common\model\system\SysUserRole;
use app\api\controller\Event;
use app\admin\logic\server\ChatsLogic;
use app\admin\logic\server\SentenceLogic;
use app\admin\logic\server\ConsumerLogic;
use app\common\model\server\Consumer;
/**
 * 系统管理员逻辑
 * Class SysUserLogic
 * @package app\admin\logic\system
 */
class SysUserLogic
    {
    public  object $auth;

    public function __construct()
    {
        $this->auth = request()->auth;
    }
    /**
     * 列表
     * @param array $param
     */
    static public function lists(array $param)
    {
        $list = SysUser::custom($param)
            ->with(['roles','groups'])
            ->append(['group_id'])
            ->order('id desc')
            ->pages($param)
            ->select();
        return list_fmt($list, SysUser::custom($param)->count());
    }
    //客服列表
    public static function serverList($user,$setting,$client_id){
        $server=self::getAll(['state'=>1]);
        if(count($server)==0) 
            return Event::sendUid($user['uid'],['type'=>'no_server','msg'=>'没有客服在线，请留言2']);
        $serverIdList = array_column($server->toArray(), 'id');
        $key=array_search($user['kefu_id'], $serverIdList);
       
        if(!empty($user['kefu_id']) && isset($key)) return SentenceLogic::getSentence($server[$key]['id'],$user['uid'],$server[$key]['is_reply']);//已分配客服
        return self::autoShare($server,$user); //随机分配
    }
    //随机分配
    public static function autoShare($server,$user){
        $rand=rand(0,count($server)-1);
        ConsumerLogic::edit(['id'=>$user['id'],'kefu_id'=>$server[$rand]['id']]);
        SentenceLogic::getSentence($server[$rand]['id'],$user['uid'],$server[$rand]['is_reply']);
        return ConsumerLogic::sendOnlineList($server[$rand]['id']);
    }
    //客服登录
    public static function serverLogin($client_id,$data){
        $service=self::details(['id'=>$data['kefu_id']]);
        if($service['state']==2) self::editUser(['id'=>$data['kefu_id'],'state'=>1]); //修改客服状态
        Event::addUid($client_id,$data['kefu_id']); //绑定ID
        session($client_id,$service->toArray());
        Event::addGroup($client_id,'serverlist'); //加入群组
    }
    //给客服提前发送消息
    public static function sendValue($data){
        Event::sendUid($data['kefu_id'], ['type'=>'sendvalue','msg'=>'成功','data'=>$data]);
    }
    /**
     * 客服列表展示与分配逻辑
     *
     * @param array $user 客户信息
     * @param array $setting 系统设置
     * @param string $client_id 客户端唯一标识
     */
    // public static function serverList($user, $setting, $client_id)
    // {
    //     $onlineServers = SysUser::where('state', 1)->select();
    //     if ($onlineServers->isEmpty()) {
    //         return Event::sendUid($user['uid'], ['type' => 'no_server', 'msg' => '没有客服在线，请留言2']);
    //     }
        
    //     if (!empty($user['kefu_id']) && in_array($user['kefu_id'], $onlineServers->pluck('id')->toArray())) {
    //         return SentenceLogic::getSentence($user['kefu_id'], $user['uid'], SysUser::find($user['kefu_id'])->is_reply);
    //     }
    //     $setting['is_auto']=2;
    //     switch ($setting['is_auto']) {
    //         case 1:
    //             return self::autoShare($onlineServers->toArray(), $user['id']);
    //         case 2:
    //             return self::autoQueue($user['uid'], $client_id);
    //         default:
    //             return Event::sendUid($user['uid'], ['type' => 'serverlist', 'msg' => '客服列表', 'data' => $onlineServers]);
    //     }
    // }

    // /**
    //  * 智能分配客服
    //  *
    //  * @param array $servers 在线客服数组
    //  * @param int $uid 客户ID
    //  */
    // private static function autoShare(array $servers, $uid)
    // {
    //     $randomIndex = rand(0, count($servers) - 1);
    //     ConsumerLogic::edit(['id' => $uid, 'kefu_id' => $servers[$randomIndex]['id']]);
    //     SentenceLogic::getSentence($servers[$randomIndex]['id'], $uid, $servers[$randomIndex]['is_reply']);
    //     return ConsumerLogic::sendOnlineList($servers[$randomIndex]['id']);
    // }

    // /**
    //  * 客户进入排队列表
    //  *
    //  * @param int $uid 客户ID
    //  * @param string $client_id 客户端唯一标识
    //  */
    // private static function autoQueue($uid, $client_id)
    // {
    //     $queueList=ConsumerLogic::getAll(['kefu_id'=>NULL]);
    //     Event::sendGroup('serverlist',['type'=>'pdlist','msg'=>'排队列表','pdlist'=>$queueList]);
    //     $uidList = array_column($queueList->toArray(), 'id');
    //     $key=array_search($v['uid'], $uidList);
    //     Event::addGroup($client_id,'pdlist');
    //     $msgList=ChatsLogic::getMsgList($uid);
    //     return Event::sendUid($uid,['type'=>'pdmsg','msg'=>'正在排队','data'=>$key+1,'msglist'=>$msgList]);
    // }

    // /**
    //  * 客服登录处理
    //  *
    //  * @param string $client_id 客户端唯一标识
    //  * @param array $data 登录数据，包含客服ID
    //  */
    // public static function serverLogin($client_id, $data)
    // {
    //     $service = SysUser::find($data['kefu_id']);
    //     if ($service->state == 2) {
    //         $service->save(['state' => 1]); // 更新状态为在线
    //     }
    //     Event::addUid($client_id, $data['kefu_id']);
    //     session($client_id, $service->toArray());
    //     Event::addGroup($client_id, 'serverlist');
    // }

    // /**
    //  * 预先向客服发送消息
    //  *
    //  * @param array $data 消息数据，包含客服ID和其他信息
    //  */
    // public static function sendValue($data)
    // {
    //     Event::sendUid($data['kefu_id'], ['type' => 'sendvalue', 'msg' => '成功', 'data' => $data]);
    // }
    /**
     * @notes  查看系统管理员详细信息
     * @param $params
     * @return array
     * @author heshihu
     * @date 2022/2/22 10:15
     */
    public static function detail($params) : array
    {
        return SysUser::findOrEmpty($params['id'])->toArray();
    }

    /**
     * 编辑
     * @param array $data
     * @param integer $id
     */
    public function edit($data)
    {

        $user = new SysUser();
        $data['updated_by'] = $this->auth->username;

        if (!empty($data['id'])) {
            SysUserGroup::where('user_id',$data['id'])->delete();
            SysUserRole::where('user_id',$data['id'])->delete();
            $user = $user::find($data['id']);
            if (!$user) {
                tips('无管理员【' . $data['username'] . '】信息');
            }
            if($data['password']){
                $data['password'] = md5(trim($data['password']));
            }else{
                unset($data['password']);
            }
            $user->update($data);
        } else {
            $data['password'] = md5(trim($data['password'] ?: SysEnum::DEFAULT_PASS));
            $this->_usernameRepeat(1, $data['username']);
            $result=SysUser::create($data);
            $data['id']=$result->id;
        }
        self::insertRole($data['role_id'],$data['id']);
        self::insertGroup($data['group_id'],$data['id']);
        return true;
    }
    public static function insertRole($data,$user_id){
        if (!empty($data)) {
            // 角色
            $roleData = [];
            foreach ($data as $roleId) {
                $roleData[] = [
                    'user_id' => $user_id,
                    'role_id' => $roleId,
                ];
            }
            (new SysUserRole())->saveAll($roleData);
        }
    }
    public static function insertGroup($data,$user_id){
        if (!empty($data)) {
            // 部门
            $data = is_array($data)?$data:explode(',',$data);
            $groupData = [];
            foreach ($data as $groupId) {
                $groupData[] = [
                    'user_id' => $user_id,
                    'group_id' => $groupId,
                ];
            }
            (new SysUserGroup())->saveAll($groupData);
        }
    }
    /**
     * 账号或电话号码查重
     * @param integer $type 类型: 1.账户 2.手机号
     * @param string $keyword
     * @param integer $id
     */
    protected function _usernameRepeat( $type,  $keyword, $id = 0)
    {
        $where = SysUser::whereIn('status', [1, 2]);
        $where->where('username|phone', $keyword);
        if ($id) {
            $where->where('id', '<>', $id);
        }
        if ($where->find()) {
            tips(($type == 1 ? '用户名' : '手机号') . '【' . $keyword . '】已被使用');
        }
    }
    /**
     * 用户密码重置
     * @param array $param
     */
    public function resetPassword(array $param): bool
    {
        $updata = [
            'password' => md5($param['encryption']),
            'updated_by' => $this->auth->username
        ];
        return SysUser::whereIn('id', $param['ids'])->update($updata) ? true : false;
    }
    /**
     * 删除
     * @param integer $id 管理员id
     */
    public function delete($id)
    {
        if (SysEnum::isSpecialAccount($id)) {
            tips('无权限');
        }
        return SysUser::whereIn('id', $id)->delete();
    }
    /**
     * 修改状态
     * @param integer $id 管理员id
     */
    public function status(int $id): bool
    {
        $user = SysUser::find($id);
        if (!$user) {
            tips('无管理员信息');
        }
        $user->status = $user->status ? 0 : 1;
        $user->created_by = $this->auth->username;
        return $user->save();
    }
    /**
     * 修改秘密
     * @param array $param
     */
    public function modifyPassword(array $param): bool
    {
        $user = SysUser::find($this->auth->uid());
        if (!$user) {
            tips('修改密码失败');
        }
        if ($user->password != md5($param['userPassword'])) {
            tips('密码不正确，修改失败');
        }
        $user->password = md5($param['confirmNewPassword']);
        return $user->save();
    }
    /**
     * 修改个人信息
     * @param array $param
     */
    public function modifyUser(array $param): bool
    {
        $user = SysUser::find($this->auth->uid);
        if (!$user) {
            tips('修改个人信息失败');
        }
        $param['id'] = $this->auth->uid;
        return $user->save($param);
    }
    public static function editUser($param){
        return !empty($param['id']) ? SysUser::update($param) : SysUser::create($param);
    }
    public static function getAll($where){
        return SysUser::where($where)->select();
    }
    public static function details($where){
        return SysUser::where($where)->find();
    }
}